<template>
     <div>
      <div ref="charts" :style="style"></div>
     </div>
</template>

<script setup name="WsChart">
import * as echarts from 'echarts'
import elementResize from 'element-resize-detector' // 尺寸监听组件
const props = defineProps({
  width:{
     type:String,
     default:'100%'
  },
  height:{
     type: String,
      default:'200px'
  },
  option:{
      type:Object,
      default:()=>( {
        xAxis: {
          type: 'category',
          data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            data: [120, 200, 150, 80, 70, 110, 130],
            type: 'bar'
          }
        ]
      })
  }
})

//通过计算属性处理width，height
const style = computed(()=>({
    width:props.width,
    height:props.height
}))

const charts = ref();
let myChart = null;
onMounted( async ()=>{
  console.log("{}",props.option)
 await initChart()
})
watch(() => props.option, (newOption) => {
  console.log("2222")
  console.log(myChart)
  if (myChart) {
    console.log("111")
    myChart.setOption(newOption);
  }
}, { deep: true });

const initChart=()=>{
    myChart = echarts.init(charts.value)
    myChart.setOption(props.option);
    // 初始化element-resize-detector组件
    var elementResizeT = elementResize({
      strategy: 'scroll', // <- 推荐监听滚动，提升性能
      callOnAdd: true // 添加侦听器时是否应调用,默认true
    })
    elementResizeT.listenTo(charts.value, function(element) {
      myChart.resize() // 当元素尺寸发生改变是会触发此事件，刷新图表
    });
  
}

</script>

<style>
</style>